package com.example.oms.controller;

import com.example.oms.dto.RegisterDto;
import com.example.oms.entity.Users;
import com.example.oms.manager.DailyQueueManager;
import com.example.oms.service.SendCodeService;
import com.example.oms.service.UserService;
import com.example.oms.utils.DataResult;
import com.example.oms.utils.JwtUtil;
import com.example.oms.utils.ValidateCodeUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private DailyQueueManager queueManager;

    @Resource
    UserService userService;
    @Resource
    SendCodeService sendCodeService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //登录
    @PostMapping("/login")
    public DataResult login(@RequestBody Users user) {
        Users user1 = userService.login(user);
        if (user1 == null) {
            return new DataResult(201, null, "用户不存在（未注册）");
        }
        if (!((user1.getPassword().equals(user.getPassword()))&&user1.getType().equals(user.getType()))) {
            return new DataResult(202, null, "密码错误");
        }
        Map<String, Object> JwtMap = new HashMap<>();
        JwtMap.put("userId",user1.getId());
        String jwt = JwtUtil.GenerateJwt(JwtMap);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("token",jwt);
        dataMap.put("id",user1.getId());
        System.out.println(user1.getType());
        if(user1.getType().equals("DOCTOR")){
            queueManager.initDoctorPeriodQueue(user1.getId());
            return new DataResult(200, dataMap, "医生登陆成功");
        }
        if(user1.getType().equals("PATIENT")){
            if(userService.checkPatientIdNumber(user1.getId())){
                return new DataResult(300,dataMap,"病人首次登录");
            }
            return new DataResult(200,dataMap,"病人登录成功");
        }
        return new DataResult(200,dataMap,"其他身份登录成功");
    }


    //注册
    @PostMapping("/register")
    public DataResult register(@RequestBody RegisterDto registerDto){
        //1. 获取用户id
        String tel = registerDto.getTel();
//      2. 获取验证码
        String code = registerDto.getCode();
//      3. 从redis中获取验证码
        String codeInRedis = redisTemplate.opsForValue().get(tel);
//      4. 进行验证码比对(页面提交的验证码和Redis中保存的验证码比对)
        if (codeInRedis != null && codeInRedis.equals(code)) {
//          5.对比成功，说明注册成功
            Users users=new Users();
            users.setAccount(tel);
            users.setPassword(registerDto.getPassword());
            if(userService.accountIsExisted(users.getAccount())){
                userService.reloadpassword(tel);
               return new DataResult(201, null, "账号已经被注册，为您修改密码为123");
            }
            userService.register(users);
            return new DataResult(200, null, "注册成功");
        }
        return new DataResult(201,null,"验证码错误");
    }

    //发送验证码
    @GetMapping("/getCode")
    public DataResult getCode(@RequestParam("tel") String tel){


        //随机生成四位验证码
        String code = ValidateCodeUtil.generateValidateCode(6).toString();
        if(!Objects.equals(tel, "")){
            if(sendCodeService.sendCodeByPhone(tel,code)){
                //往redis中设置数据：key、value、过期值、过期时间单位  MINUTES代表分钟
                redisTemplate.opsForValue().set(tel, code,5, TimeUnit.MINUTES);
                return new DataResult(200,tel,"短信发送成功"+code);
            }
            redisTemplate.opsForValue().set(tel, code,5, TimeUnit.MINUTES);
            return new DataResult(200,null,"短信发送成功"+code);
        }
        else {
            return new DataResult(203,null,"手机号为空");
        }
    }
}
